package controller

import (
	"fmt"
	"path"
	"path/filepath"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"lab.com/conf"
	"lab.com/define/errorcode"
	"lab.com/request"
	"lab.com/utils"
)

type cUpload struct {
	APIBase
}

// Upload .
var Upload = cUpload{}

// FilesUpload 文件上传
func (upload *cUpload) FilesUpload(c *gin.Context) {
	inputParams := request.FileUploadReq{}
	if err := inputParams.CheckInputParams(c); err != nil {
		upload.Resp(c, nil, err)
		return
	}
	// Multipart form
	form, err := c.MultipartForm()
	if err != nil {
		upload.Resp(c, nil, errorcode.New(errorcode.ErrParams, errorcode.ErrParamsMsg, nil))
		return
	}

	files := form.File["files"]

	if files == nil {
		upload.Resp(c, nil, errorcode.New(errorcode.ErrParams, "未上传文件", nil))
		return
	}

	links := make([]string, 0, len(files))

	for i := 0; i < len(files); i++ {
		filename := filepath.Base(files[i].Filename)
		extension := path.Ext(filename)

		/*if extension != ".jpeg" && extension != ".jpg" && extension != ".svg" && extension != ".png" && extension != ".pdf" {
			api.Resp(c, nil, errorcode.New(errorcode.ErrParams, "文件类型错误", nil))
			return
		}
		*/
		file, err := files[i].Open()
		if err != nil {
			upload.Resp(c, nil, err)
			return
		}

		randFileName := utils.RandString(8) + fmt.Sprintf("%d", time.Now().Unix()) + extension
		link, err := utils.UploadFileToCos(file, randFileName, utils.GetDirByType(inputParams.DirType))
		if err != nil {
			upload.Resp(c, nil, err)
			return
		}
		links = append(links, link)
	}

	upload.Resp(c, map[string]interface{}{"list": links}, err)
}

// FilesUploadToServer 文件上传至服务器
func (upload *cUpload) FilesUploadToServer(c *gin.Context) {
	inputParams := request.FileUploadReq{}
	if err := inputParams.CheckInputParams(c); err != nil {
		upload.Resp(c, nil, err)
		return
	}
	// Multipart form
	form, err := c.MultipartForm()
	if err != nil {
		upload.Resp(c, nil, errorcode.New(errorcode.ErrParams, errorcode.ErrParamsMsg, nil))
		return
	}

	files := form.File["files"]

	if files == nil {
		upload.Resp(c, nil, errorcode.New(errorcode.ErrParams, "未上传文件", nil))
		return
	}

	links := make([]string, 0, len(files))

	for i := 0; i < len(files); i++ {
		filename := filepath.Base(files[i].Filename)
		extension := path.Ext(filename)
		file, err := files[i].Open()
		if err != nil {
			upload.Resp(c, nil, err)
			return
		}

		randFileName := utils.RandString(8) + fmt.Sprintf("%d", time.Now().Unix()) + extension
		path, err := utils.UploadFileToServer(file, randFileName, utils.GetDirByType(inputParams.DirType))
		if err != nil {
			upload.Resp(c, nil, err)
			return
		}
		link := conf.ServerConf.Host + ":" + strconv.Itoa(conf.ServerConf.Port) + "/" + path
		links = append(links, link)
	}

	upload.Resp(c, map[string]interface{}{"list": links}, err)
}
